package com.weipt.controller;

import com.weipt.security.CustomAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author weipt
 * @description 处理登录请求，用controller或者filter都可以，建议controller，更加清晰
 * 如果用filter，继承AbstractAuthenticationProcessingFilter，有三个方法
 * 上下文放authentication
 * 成功处理
 * 失败处理
 * @date 2024/9/3 22:55
 */

@Controller
public class JspController {

    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    RememberMeServices rememberMeServices;

    //此处处理登录，可以用controller，也可以用filter，比如实现AbstractAuthenticationProcessingFilter
    @PostMapping("/handleLogin")
    public String handleLogin(String username, String password, HttpServletRequest request, HttpServletResponse resp){
        //此处我们可以利用一个标记，控制本地校验还是oauth2校验，oauth2一般是访问远程链接，然后提前配置好回调，解析回调头信息

        String redirectUrl = "redirect:/error.jsp";
        try {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
            //这一行代码调用起来认证
            Authentication authentication = customAuthenticationProvider.authenticate(token);
            if(authentication!=null && authentication.isAuthenticated()){
                SecurityContextHolder.getContext().setAuthentication(token);  //这一步很关键
                rememberMeServices.loginSuccess(request, resp, authentication);  //讲remember-me信息返回前端
                redirectUrl =  "redirect:/index.jsp";  //利用redirect，不然浏览器地址栏不变化，如果在index.jsp里面，我们就不用redirect
            }else{
                rememberMeServices.loginFail(request, resp);
            }
        }catch (Exception e){
            rememberMeServices.loginFail(request, resp);
        }
        return redirectUrl;
    }
}
